import 'dart:async';

import 'package:flutter/material.dart';

class FutureBuilderTest extends StatefulWidget {
  @override
  _FutureBuilderTestState createState() => _FutureBuilderTestState();
}

class _FutureBuilderTestState extends State<FutureBuilderTest> {
  @override
  Widget build(BuildContext context) {
    String initData = "初始数据";

    StreamController _streamController = StreamController();
    int count = 0;

    return Scaffold(
      appBar: AppBar(title: Text('首页')),
      body: Center(
        child: StreamBuilder(
//            future: getMockData(),
//            initialData: initData,
            stream: _streamController.stream,
            builder: (context, snapshot) {
              if (snapshot.hasError) return Text('Error: ${snapshot.error}');
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('没有Stream');
                case ConnectionState.waiting:
                  return Text('等待数据...');
                case ConnectionState.active:
                  return Text('active: ${snapshot.data}');
                case ConnectionState.done:
                  return Text('Stream已关闭');
              }
              return null; // unreachable
            }),
      ),
      floatingActionButton:
          FloatingActionButton(onPressed: () {
            _streamController.sink.add(count++);
          }, child: Icon(Icons.add)),
    );
  }

  // 获取模拟的数据
  Future<String> getMockData() {
    return Future.delayed(Duration(seconds: 2), () {
      return "返回一段数据到前端";
    });
  }

  Stream<int> counter() {
    var interval = Duration(seconds: 1);
    // 返回一个事件流
    Stream<int> stream = Stream.periodic(interval, (i) {
      return i;
    });
    // 事件流只执行5次
//    stream = stream.take(5);
    // 通过里面的值来判断结束
    stream = stream.takeWhile((element) => element < 5);
    // 跳过2
    // stream = stream.skip(2);
    // 跳过一定条件的事件
    // stream = stream.skipWhile((data) => data<5);
    // 将流中所有的数据收集存放在List中，并返回 Future<List>对象，listData里面 0-9
    //1.这个是一个异步方法，要结果则需要使用await关键字
    //2.这个是等待Stream当流结束时，一次返回结果
    // Future<List<int>> future = stream.toList();
    // 类似for循环
//    stream.listen((event) {
//      print(event);
//    }, onError: (error) {
//      print("失败");
//    }, onDone: () {
//      print("成功");
//    });

    //StreamController里面会创建一个Stream，我们实际操控的Stream
    StreamController<String> streamController = StreamController();
    streamController.stream.listen((data) => print(data));
    streamController.sink.add("aaa");
    streamController.add("bbb");
    streamController.add("ccc");
    streamController.close();

    return stream;
  }

  void _stream() async {
    Duration interval = Duration(seconds: 1);
    Stream<int> stream = Stream.periodic(interval, (data) => data);
    stream = stream.take(10); //指定发送事件个数
    await for (int i in stream) {
      print(i);
    }
  }
}
